package com.kgc.sportscircle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;

import com.kgc.sportscircle.pojo.Sportsuser;
import com.kgc.sportscircle.service.SportsuserService;
import com.kgc.sportscircle.utils.PasswordEncrypt;
import com.kgc.sportscircle.utils.Utility;
import com.kgc.sportscircle.utils.ZxHttpUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class RegisterController {

    @Resource
    private StringRedisTemplate template;
    @Reference(version ="1.11")

    private SportsuserService sportsuserService;

    @RequestMapping("/getValidCode.do")
    public Map getValidCode(String mobile,HttpServletRequest request) throws IOException {
        Map result = new HashMap();
        result.put("flag",false);
        if (!mobile.matches("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$")){
            result.put("msg","手机格式不对");
            return result;
        }
        //判读手机号是否被注册
        if (sportsuserService.verifyMobile(mobile)!=0){
            result.put("msg","手机号已存在");
            return result;
        }
        String account = "18952148257";
        String ts =  Utility.getNowDateStr();
        String pswd="Lzy80983806";
        String NeedStatus = "true";
        pswd = Utility.getMD5(account + pswd + ts);
        Random rd = new Random();
        String validCode = ""+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10)+rd.nextInt(10);
        System.out.println("验证码"+validCode);
        String msg = "您的验证码为："+validCode+",如非本人操作请忽略。";
        Map params = new HashMap();
        params.put("account",account);
        params.put("pswd",pswd);
        params.put("mobile",mobile);
        params.put("msg",msg);
        params.put("ts",ts);
        params.put("needstatus",NeedStatus);


        //通过短信平台发送短信
        String rep = ZxHttpUtil.sendPostMessage("http://139.196.108.241:8080/Api/HttpSendSMYzm.ashx", params, "UTF-8");
        Map reply = JSON.parseObject(rep,Map.class);
        if((Integer)reply.get("result")==0){
            //如果短信平台发送成功，把验证码保存到redis缓存中，有效时间是30秒

            result.put("flag",true);
            result.put("msg","验证码已发送，请在30秒内输入");    //返回页面信息都是在result中的
       /*     HttpSession session = request.getSession();
            String sessionId =session.getId();
            session.setAttribute(sessionId,validCode);
            session.setMaxInactiveInterval(300);*/
            template.opsForValue().set("login:validCode:"+mobile,validCode,300, TimeUnit.SECONDS);
            return result;
        }else{
            //如果短信平台发送失败，提示
           // Map result = new HashMap();
            result.put("flag",false);
            result.put("msg","验证码发送失败");
            return result;
        }
    }

    @RequestMapping("/checkValidCode.do")
    public Map getValidCode(String mobile,String validCode,String password,HttpServletRequest request) throws IOException {
        System.out.println(password);
        Map result = new HashMap();
        result.put("flag",false);
        result.put("msg","验证码无效或已过期");
        if (!mobile.matches("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$")){
            result.put("msg","手机格式不对");
            return result;
        }
        //从redis缓存中获取该手机号对应的验证码
        String right = template.opsForValue().get("login:validCode:"+mobile);
        if (!password.matches("^[a-zA-Z]\\w{5,17}$")){
            result.put("msg","密码要以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
            return result;
        }
        if(right==null){//如果redis缓存中没有该手机号对应的key/value
            return result;
        }
        System.out.println(validCode.toString()+" : "+right.toString());
        if(validCode.toString().equals(right.toString())) {
            result.put("flag",true);
            result.put("msg","验证码正确");
            template.delete("login:validCode:"+mobile);
            //创建新的用户对象，存到数据库
            Sportsuser sportsuser = new Sportsuser();
            sportsuser.setMobile(mobile);
            //md5加密保存用户密码
            sportsuser.setPassword(PasswordEncrypt.encodeByMd5(password));
            //两种状态：1.手机号已存在返回状态码-1，2手机号不存在返回状态码1
            int state = sportsuserService.register(sportsuser);
            result.put("state",state);
        }
        return result;
    }
}
